package com.suixun.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.velocity.texen.util.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.authority.common.MD5Util;
import com.google.gson.Gson;
import com.suixun.Result;
import com.suixun.dao.StdDeviceinfoMapper;
import com.suixun.dao.StdObjectinfoMapper;
import com.suixun.dao.StdPeopleObjectMapper;
import com.suixun.dao.StdPeopleWXMapper;
import com.suixun.dao.StdPeopleinfoMapper;
import com.suixun.dao.devicemanage.DeviceServiceDAO;
import com.suixun.dao.parentmanage.ParentManageDAO;
import com.suixun.dao.studentmanage.StudentManageDAO;
import com.suixun.entity.ParentInfo;
import com.suixun.entity.StdDeviceinfo;
import com.suixun.entity.StdDeviceinfoExample;
import com.suixun.entity.StdObjectinfo;
import com.suixun.entity.StdObjectinfoExample;
import com.suixun.entity.StdPeopleObject;
import com.suixun.entity.StdPeopleObjectExample;
import com.suixun.entity.StdPeopleWX;
import com.suixun.entity.StdPeopleWXExample;
import com.suixun.entity.StdPeopleinfo;
import com.suixun.entity.StdPeopleinfoExample;
import com.suixun.entity.ext.ExtStdObjectinfo;
import com.suixun.entity.form.ParentForm;
import com.suixun.entity.jxt.JxtResult;
import com.suixun.entity.jxt.Teacher0;
import com.suixun.entity.mongodb.DeviceCache;
import com.suixun.entity.mongodb.UserCache;
import com.suixun.entity.page.PageModel;
import com.suixun.jxt.service.JxtService;
import com.suixun.jxt.service.JxtTeacherService;
import com.suixun.service.ObjectService;
import com.suixun.service.ParentService;
import com.suixun.service.cache.CacheService;
import com.suixun.service.mongodb.DeviceCacheService;
import com.suixun.service.mongodb.UserCacheService;
import com.suixun.util.ExcelUtil;
import com.suixun.util.HttpUtil;
import com.suixun.util.StringUtil;
import com.suixun.vo.ChangeParentTel;
import com.suixun.vo.ParentVO;

import rop.thirdparty.org.apache.commons.lang3.StringUtils;

/**
 * 
 * <p>
 * Title: ParentServiceImpl
 * </p>
 * <p>
 * 功能描述:家长信息业务层
 * </p>
 * 
 * @author 陈显强
 * @date 2016年12月12日下午3:00:01
 * @version 1.0
 */
@Service("parentService")
public class ParentServiceImpl implements ParentService {
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private ParentManageDAO parentManageDAO;
	@Resource
	private UserCacheService userCacheService;
	@Resource
	private StdPeopleinfoMapper stdPeopleinfoMapper;
	@Resource
	private StdPeopleWXMapper stdPeopleWXMapper;
	@Resource
	private ObjectService objectService;
	@Resource
	private JxtTeacherService jxtTeacherService;
	@Resource
	private DeviceCacheService deviceCacheService;
	@Resource
	private DeviceServiceDAO deviceServiceDAO;
	@Resource
	private StdObjectinfoMapper stdObjectinfoMapper;
	@Resource
	private JxtService jxtService;
	@Resource
	private CacheService cacheService;
	@Resource
	private StudentManageDAO studentManageDAO;
	@Resource
	private StdPeopleObjectMapper stdPeopleObjectMapper;
	@Resource
	private StdDeviceinfoMapper stdDeviceinfoMapper;

	/**
	 * 
	 * <p>
	 * Title: updateTel
	 * </p>
	 * <p>
	 * 功能描述:修改家长手机号码
	 * </p>
	 * 
	 * @param people
	 * @return
	 * 
	 */
	@Override
	@Transactional
	public String updateParentTel(ParentForm parent) {
		if (StringUtil.isBlank(parent.getParentid()) || StringUtil.isBlank(parent.getParentphone())) {
			return "必要参数为空";
		}
		// 查询parentid是存在
		Integer peopleid = null;
		try {
			peopleid = Integer.parseInt(parent.getParentid());
		} catch (NumberFormatException e) {
			return "家长id格式不符";
		}
		StdPeopleinfo peopleinfo = stdPeopleinfoMapper.selectByPrimaryKey(peopleid);
		if (peopleinfo == null || peopleinfo.getIsdeleted()) {
			return "家长不存在";
		}
		String oldPeopletel = peopleinfo.getPeopletel();
		// 查询新手机号是否已存在
		StdPeopleinfoExample stdPeopleinfoExample = new StdPeopleinfoExample();
		stdPeopleinfoExample.createCriteria().andIsdeletedEqualTo(false).andPeopletelEqualTo(parent.getParentphone());
		List<StdPeopleinfo> peopleList = stdPeopleinfoMapper.selectByExample(stdPeopleinfoExample);
		// 同步家校通
		String result = synJxtForUpdateTel(peopleid, oldPeopletel, parent.getParentphone());
		if (result != null) {
			return result;
		}
		// 清除旧手机号下的所有缓存
		flushBabyCache(oldPeopletel, peopleid);
		if (CollectionUtils.isEmpty(peopleList)) {
			// 新手机号不存在，则直接修改
			updateMobileByAccountNotExist(peopleid, parent.getParentphone());
		} else {
			updateMobileByAccountExist(peopleList.get(0).getPeopleid(), peopleid, parent.getParentphone(),
					oldPeopletel);
		}
		return null;
	}

	private void updateMobileByAccountExist(Integer newPeopleid, Integer oldPeopleid, String newPeopletel,
			String oldPeopletel) {
		// 清除新手机号下的所有缓存
		flushBabyCache(newPeopletel, newPeopleid);
		// 新手机号已存在，则将旧手机号下的设备转移到新手机号下
		List<StdObjectinfo> objectinfoList = studentManageDAO.getStudentListByparentTel(oldPeopletel);
		if (!CollectionUtils.isEmpty(objectinfoList)) {
			StdPeopleObjectExample stdPeopleObjectExample = null;
			List<StdPeopleObject> stdPeopleObjectList = null;
			StdDeviceinfoExample stdDeviceinfoExample = null;
			List<StdDeviceinfo> stdDeviceinfoList = null;
			List<StdPeopleObject> tempPeopleObjectList = null;
			StdObjectinfoExample stdObjectinfoExample = null;
			List<StdObjectinfo> tempObjectinfoList = null;
			for (StdObjectinfo stdObjectinfo : objectinfoList) {
				// 修改std_people_object表
				stdPeopleObjectExample = new StdPeopleObjectExample();
				stdPeopleObjectExample.createCriteria().andPeopleidEqualTo(oldPeopleid)
						.andObjectidEqualTo(stdObjectinfo.getObjectid());
				stdPeopleObjectList = stdPeopleObjectMapper.selectByExample(stdPeopleObjectExample);
				if (!CollectionUtils.isEmpty(stdPeopleObjectList)) {
					for (StdPeopleObject stdPeopleObject : stdPeopleObjectList) {
						// 先删除，再新增
						if(!"班主任".equals(stdPeopleObject.getFamilystatus())) {
							stdPeopleObjectMapper.deleteByPrimaryKey(stdPeopleObject.getId());
							// 如果新的手机号也是当前学生的监护人，再判断旧手机号是否是当前学生的主监护人，若是，则删除新手机号与学生的关系，在更新新手机号与学生的关系，若不是，则只删除旧手机号与学生的关系即可
							stdPeopleObjectExample = new StdPeopleObjectExample();
							stdPeopleObjectExample.createCriteria().andPeopleidEqualTo(newPeopleid)
									.andObjectidEqualTo(stdPeopleObject.getObjectid()).andFamilystatusEqualTo(stdPeopleObject.getFamilystatus());
							tempPeopleObjectList = stdPeopleObjectMapper.selectByExample(stdPeopleObjectExample);
							if (!CollectionUtils.isEmpty(tempPeopleObjectList)) {
								stdObjectinfoExample = new StdObjectinfoExample();
								stdObjectinfoExample.createCriteria().andObjectidEqualTo(stdPeopleObject.getObjectid())
										.andPeopleidEqualTo(oldPeopleid).andIsdeletedEqualTo(false);
								tempObjectinfoList = stdObjectinfoMapper.selectByExample(stdObjectinfoExample);
								if (!CollectionUtils.isEmpty(tempObjectinfoList)) {
									stdPeopleObjectMapper.deleteByPrimaryKey(tempPeopleObjectList.get(0).getId());
								} else {
									continue;
								}
							}
							stdPeopleObject.setPeopleid(newPeopleid);
							stdPeopleObject.setCreatetime(new Date());
							stdPeopleObjectMapper.insertSelective(stdPeopleObject);
						}
					}
				}
				// 修改std_objectinfo表
				if (oldPeopleid.toString().equals(String.valueOf(stdObjectinfo.getPeopleid()))) {
					stdObjectinfo.setPeopleid(newPeopleid);
					stdObjectinfo.setUpdatetime(new Date());
					stdObjectinfoMapper.updateByPrimaryKeySelective(stdObjectinfo);
				}
				// 修改std_deviceinfo表
				stdDeviceinfoExample = new StdDeviceinfoExample();
				stdDeviceinfoExample.createCriteria().andPeopleidEqualTo(oldPeopleid)
						.andObjectidEqualTo(stdObjectinfo.getObjectid()).andIsdeletedEqualTo(0);
				stdDeviceinfoList = stdDeviceinfoMapper.selectByExample(stdDeviceinfoExample);
				if (!CollectionUtils.isEmpty(stdDeviceinfoList)) {
					for (StdDeviceinfo stdDeviceinfo : stdDeviceinfoList) {
						stdDeviceinfo.setPeopleid(newPeopleid);
						stdDeviceinfo.setUpdatetime(new Date());
						stdDeviceinfoMapper.updateByPrimaryKeySelective(stdDeviceinfo);
					}
				}
			}
		}
	}

	private void updateMobileByAccountNotExist(Integer peopleid, String newPeopletel) {
		StdPeopleinfo stdPeopleinfo = new StdPeopleinfo();
		stdPeopleinfo.setUpdatetime(new Date());
		stdPeopleinfo.setPeopletel(newPeopletel);
		stdPeopleinfo.setPeopleid(peopleid);
		stdPeopleinfoMapper.updateByPrimaryKeySelective(stdPeopleinfo);
	}

	private void flushBabyCache(Integer babyid, Integer peopleid) {
		cacheService.flushBabys(getGuardiansByObjectId(babyid));
		cacheService.flushBaby(babyid);
		cacheService.flushFullBaby(peopleid, babyid);
	}

	// 清除手机号下的所有学生的缓存
	private void flushBabyCache(String peopletel, Integer peopleid) {
		List<StdObjectinfo> tempObjectinfoList = studentManageDAO.getStudentListByparentTel(peopletel);
		if (!CollectionUtils.isEmpty(tempObjectinfoList)) {
			for (StdObjectinfo stdObjectinfo : tempObjectinfoList) {
				flushBabyCache(stdObjectinfo.getObjectid(), peopleid);
			}
		}
	}

	/**
	 * <p>
	 * Title: synJxtForUpdateTel
	 * </p>
	 * <p>
	 * 功能描述: 同步家长手机号到家校通
	 * </p>
	 * 
	 * @param peopleid
	 * @param oldPeopletel
	 * @param peopletel
	 * @return
	 */
	private String synJxtForUpdateTel(Integer peopleid, String oldPeopletel, String peopletel) {
		// 家校通那边只保存了主监护人的手机号与学生姓名关联的账户，普通监护人是不会保存的
		StdObjectinfoExample stdObjectinfoExample = new StdObjectinfoExample();
		stdObjectinfoExample.createCriteria().andPeopleidEqualTo(peopleid).andIsdeletedEqualTo(false);
		List<StdObjectinfo> objectinfoList = stdObjectinfoMapper.selectByExample(stdObjectinfoExample);
		if (!CollectionUtils.isEmpty(objectinfoList)) {
			// 查询原手机号
			StdPeopleinfo stdPeopleinfo = stdPeopleinfoMapper.selectByPrimaryKey(peopleid);
			if (stdPeopleinfo != null && !stdPeopleinfo.getIsdeleted()) {
				// 家校通那边只保存了主监护人的手机号与学生姓名关联的账户，普通监护人是不会保存的
				JxtResult jxtResult = null;
				for (StdObjectinfo stdObjectinfo : objectinfoList) {
					final Integer jxtBabyId = stdObjectinfo.getJxtBabyid();
					if (jxtBabyId != null) {
						jxtResult = jxtService.modifyBabyParentMobile(oldPeopletel, peopletel, jxtBabyId);
						if (jxtResult == null) {
							return "同步家校通失败";
						}
						if (!"操作成功".equals(String.valueOf(jxtResult.getMsg()))) {
							return String.format("同步家校通失败：%s", jxtResult.getMsg());
						}
					}
				}
			}
		}
		//班主任或教师身份，需要在家校通再做一次修改，这里就不做同步了
		/*//判断当前旧手机号如果是班主任角色，则需要同步到家校通
		StdPeopleObjectExample stdPeopleObjectExample = new StdPeopleObjectExample();
		stdPeopleObjectExample.createCriteria().andPeopleidEqualTo(peopleid).andFamilystatusEqualTo("班主任");
		if(!CollectionUtils.isEmpty(stdPeopleObjectMapper.selectByExample(stdPeopleObjectExample))) {
			JxtResult jxtResult = jxtService.modifyHeadmasterMobile(oldPeopletel, peopletel);
			if (jxtResult == null) {
				return "同步家校通失败";
			}
			if (!"操作成功".equals(String.valueOf(jxtResult.getMsg()))) {
				return String.format("同步家校通失败：%s", jxtResult.getMsg());
			}
		}*/
		return null;
	}
	/*
	 * public String updateParentTel(ParentForm parent) { if
	 * (StringUtil.isBlank(parent.getParentid()) ||
	 * StringUtil.isBlank(parent.getParentphone())) { return "必要参数为空"; }
	 * StdPeopleinfo people = new StdPeopleinfo(); Integer peopleid =
	 * Integer.parseInt(parent.getParentid()); people.setPeopleid(peopleid);
	 * people.setPeopletel(parent.getParentphone()); try { // 同步到家校通 //
	 * 查询当前手机号是否已绑定学生 StdObjectinfoExample stdObjectinfoExample = new
	 * StdObjectinfoExample();
	 * stdObjectinfoExample.createCriteria().andPeopleidEqualTo(peopleid).
	 * andIsdeletedEqualTo(false); List<StdObjectinfo> objectinfoList =
	 * stdObjectinfoMapper.selectByExample(stdObjectinfoExample); if
	 * (!CollectionUtils.isEmpty(objectinfoList)) { // 查询原手机号 StdPeopleinfo
	 * stdPeopleinfo = stdPeopleinfoMapper.selectByPrimaryKey(peopleid); if
	 * (stdPeopleinfo != null && !stdPeopleinfo.getIsdeleted()) { String
	 * oldPeopletel = stdPeopleinfo.getPeopletel(); //
	 * 家校通那边只保存了主监护人的手机号与学生姓名关联的账户，普通监护人是不会保存的 JxtResult jxtResult = null; for
	 * (StdObjectinfo stdObjectinfo : objectinfoList) { final Integer jxtBabyId
	 * = stdObjectinfo.getJxtBabyid(); if (jxtBabyId != null) { jxtResult =
	 * jxtService.modifyBabyParentMobile(oldPeopletel, parent.getParentphone(),
	 * jxtBabyId); if (jxtResult == null) { return "同步家校通失败"; } if
	 * (!"操作成功".equals(String.valueOf(jxtResult.getMsg()))) { return
	 * String.format("同步家校通失败：%s", jxtResult.getMsg()); } } } } }
	 * 
	 * // 修改手机号 parentManageDAO.update(people); // 清缓存 if
	 * (!CollectionUtils.isEmpty(objectinfoList)) { for (StdObjectinfo
	 * stdObjectinfo : objectinfoList) {
	 * cacheService.flushBabys(getGuardiansByObjectId(stdObjectinfo.getObjectid(
	 * ))); cacheService.flushFullBaby(peopleid, stdObjectinfo.getObjectid()); }
	 * }
	 * 
	 * String param = new
	 * StringBuffer().append("userid=").append(parent.getParentid()).
	 * append("&telephone=") .append(parent.getParentphone()).toString(); String
	 * url = new
	 * StringBuffer().append(Constants.getApiUrl()).append(Constant.API.
	 * UPDATE_PEOPLE_TEL) .toString(); // 刷新缓存 HttpUtil.sendGet(url, param);
	 * 
	 * } catch (Exception e) { return "操作失败"; } return null; }
	 */

	/**
	 * 
	 * <p>
	 * Title: telIsExsit
	 * </p>
	 * <p>
	 * 功能描述:判断手机号是否存在
	 * </p>
	 * 
	 * @return
	 */
	public String telIsExsit(String parentPhone) {
		return parentManageDAO.queryTel(parentPhone);
	}

	/**
	 * 
	 * <p>
	 * Title: queryOldTel
	 * </p>
	 * <p>
	 * 功能描述:获取修改前的手机号
	 * </p>
	 * 
	 * @param parent
	 * @return
	 */
	public String queryOldTel(String parentid) {
		StdPeopleinfo people = new StdPeopleinfo();
		people.setPeopleid(Integer.parseInt(parentid));
		return parentManageDAO.queryOldTel(people);
	}

	/**
	 * 
	 * <p>
	 * Title: updateParentPassword
	 * </p>
	 * <p>
	 * 功能描述:修改密码
	 * </p>
	 * 
	 * @param parent
	 * @return
	 * 
	 */
	public int updateParentPassword(ParentForm parent) {
		if (readyUpdatePassword(parent, 1) == -1) {
			return -1;
		}
		StdPeopleinfo people = new StdPeopleinfo();
		people.setPassword(parent.getPassword());
		people.setPeopleid(Integer.parseInt(parent.getParentid()));
		return parentManageDAO.update(people);
	}

	/**
	 * <p>
	 * Title: queryList
	 * </p>
	 * <p>
	 * 功能描述:按条件查询家长信息
	 * </p>
	 * 
	 * @param parent
	 * @return
	 * 
	 */

	@Override
	public PageModel<ParentVO> queryList(ParentForm parent) throws SQLException {
		String parentname = null, parentphone = null;
		PageModel<ParentVO> pageModel = new PageModel<ParentVO>();
		if (parent != null) {
			if (StringUtil.isNotEmpty(parent.getParentname())) {
				parentname = StringUtil.append(parent.getParentname());
			}
			if (StringUtil.isNotEmpty(parent.getParentphone())) {
				parentphone = StringUtil.append(parent.getParentphone());
			}
			if (StringUtil.isNotEmpty(parent.getPagecount())) {
				pageModel.setPagesize(Integer.parseInt(parent.getPagecount()));
			}
		}
		pageModel.getQueryparam().put("parentname", parentname);
		pageModel.getQueryparam().put("parentphone", parentphone);
		if (parent.getUserid() != null) {
			pageModel.getQueryparam().put("organ", true);
			pageModel.getQueryparam().put("userid", parent.getUserid());
		}
		Integer totleRows = parentManageDAO.countRows(pageModel);
		pageModel.setTotlepage(totleRows);
		if (parent != null) {
			if (StringUtil.isNotEmpty(parent.getPagenumber())) {
				pageModel.setCurrentpage(Integer.parseInt(parent.getPagenumber()));
			}
		}
		List<ParentInfo> parents = parentManageDAO.queryByPaging(pageModel);
		List<ParentVO> parentVOs = new LinkedList<>();
		for (ParentInfo parentinfo : parents) {
			ParentVO parentVO = new ParentVO();
			parentVOs.add(toParentVO(parentinfo, parentVO));
			parentVO = null;
		}
		pageModel.setQueryresult(parentVOs);
		return pageModel;
	}

	/**
	 * 
	 * <p>
	 * Title: toParentVO
	 * </p>
	 * <p>
	 * 功能描述:将ParentInfo转换为ParentVO方便页面展示
	 * </p>
	 * 
	 * @param parentinfo
	 * @param parentVO
	 * @return
	 */
	public ParentVO toParentVO(ParentInfo parentinfo, ParentVO parentVO) {
		parentVO.setMdtid(!StringUtil.isNotEmpty(parentinfo.getMdtid()) ? null : parentinfo.getMdtid());
		parentVO.setPeopleid(parentinfo.getPeopleid() == null ? null : parentinfo.getPeopleid().toString());
		parentVO.setHomeaddr(!StringUtil.isNotEmpty(parentinfo.getHomeaddr()) ? null : parentinfo.getHomeaddr());
		parentVO.setPeopleidcard(
				!StringUtil.isNotEmpty(parentinfo.getPeopleidcard()) ? null : parentinfo.getPeopleidcard());
		parentVO.setPeoplename(!StringUtil.isNotEmpty(parentinfo.getPeoplename()) ? null : parentinfo.getPeoplename());
		parentVO.setPeopletel(!StringUtil.isNotEmpty(parentinfo.getPeopletel()) ? null : parentinfo.getPeopletel());
		parentVO.setFamilystatus(
				!StringUtil.isNotEmpty(parentinfo.getFamilystatus()) ? null : parentinfo.getFamilystatus());
		parentVO.setParentid(parentinfo.getParentid() == null ? null : parentinfo.getParentid().toString());
		parentVO.setIspush(parentinfo.getIspush() == null ? null : parentinfo.getIspush().toString());
		parentVO.setPeopletype(parentinfo.getPeopletype() == null ? null : String.valueOf(parentinfo.getPeopletype()));
		return parentVO;
	}

	/**
	 * 
	 * <p>
	 * Title: readyUpdatePassword
	 * </p>
	 * <p>
	 * 功能描述:修改前验证用户id，手机号，imei号是否匹配 ，不能匹配则无法修改
	 * </p>
	 * 
	 * @param parent
	 * @return
	 * 
	 */
	@Override
	public int readyUpdatePassword(ParentForm parent, int type) {
		if (!StringUtil.isNotEmpty(parent.getParentid()) || !StringUtil.isNotEmpty(parent.getParentphone())
				|| !StringUtil.isNotEmpty(parent.getMdtid())) {
			return -1;
		}
		ParentInfo parentInfo = new ParentInfo();
		parentInfo.setMdtid(parent.getMdtid());
		parentInfo.setPeopleid(Integer.parseInt(parent.getParentid()));
		if (type == 1) {
			parentInfo.setPeopletel(parent.getParentphone());
		}
		if (CollectionUtils.isEmpty(parentManageDAO.queryByIdOrTelOrImei(parentInfo))) {
			return -1;
		}
		return 0;
	}

	/**
	 * <p>
	 * Title: queryParents
	 * </p>
	 * <p>
	 * 功能描述:通过设备号查询家长信息
	 * </p>
	 * 
	 * @param parent
	 * @return
	 */
	@Override
	public List<ParentVO> queryParents(ParentForm parent) {
		String mdtid = null, simid = null;
		if (StringUtil.isNotEmpty(parent.getMdtid())) {
			mdtid = parent.getMdtid();
		}
		if (StringUtil.isNotEmpty(parent.getSimid())) {
			simid = parent.getSimid();
		}
		Map<String, Object> map = new HashMap<>();
		map.put("mdtid", mdtid);
		map.put("simid", simid);
		List<ParentInfo> parents = parentManageDAO.queryByParam(map);
		List<ParentVO> parentVOs = new LinkedList<>();
		for (ParentInfo parentinfo : parents) {
			ParentVO parentVO = new ParentVO();
			parentVOs.add(toParentVO(parentinfo, parentVO));
			parentVO = null;
		}
		return parentVOs;
	}

	/*
	 * 刷新设备的缓存
	 */
	@Override
	public UserCache refreshUserCache(Integer peopleid, String telephone) {
		try {

			List<UserCache> userCaches = userCacheService.find(new Query(Criteria.where("userid").is(peopleid)));
			if (userCaches != null && userCaches.size() > 0) {
				Update update = new Update();
				update.set("telephone", telephone);
				return userCacheService.findAndModify(new Query(Criteria.where("userid").is(peopleid)), update);
			} else {
				UserCache userCache = new UserCache();
				userCache.setTelephone(telephone);
				userCache.setUserid(peopleid);
				return userCacheService.save(userCache);
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}

	@Override
	public UserCache refreshUserCache(Integer peopleid) {
		try {
			StdPeopleinfo stdPeopleinfo = stdPeopleinfoMapper.selectByPrimaryKey(peopleid);
			Teacher0 teacher0 = jxtTeacherService.getTeacherInfoFromJxtBytel(stdPeopleinfo.getParentid(),
					stdPeopleinfo.getPeopletel(), stdPeopleinfo.getPeoplename());
			stdPeopleinfo.setSchoolid(teacher0.getSchoolid());
			stdPeopleinfo.setClassname(teacher0.getClassname().replace(",", ""));
			if (stdPeopleinfo != null) {
				StdPeopleWXExample stdPeopleWXExample = new StdPeopleWXExample();
				stdPeopleWXExample.createCriteria().andPeopleidEqualTo(peopleid);
				stdPeopleWXExample.setOrderByClause(" id desc ");
				String openid = "";
				List<StdPeopleWX> ents = stdPeopleWXMapper.selectByExample(stdPeopleWXExample);
				if (ents != null && ents.size() > 0) {
					openid = ents.get(0).getOpenid();
				}

				userCacheService.findAllAndRemove(new Query(Criteria.where("userid").is(peopleid)));
				UserCache userCache = new UserCache();
				userCache.setTelephone(stdPeopleinfo.getPeopletel());
				userCache.setUserid(peopleid);
				userCache.setUsername(stdPeopleinfo.getPeoplename());
				userCache.setSchoolid(stdPeopleinfo.getSchoolid());
				userCache.setWxopenid(openid);
				String babyids = "";
				List<ExtStdObjectinfo> babys = objectService.getBabys(peopleid, 2);
				if (babys != null) {
					for (ExtStdObjectinfo baby : babys) {
						babyids = babyids + baby.getObjectid() + ",";
					}
					userCache.setBabyids(StringUtil.trim(babyids, ','));
				}
				return userCacheService.save(userCache);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * <p>
	 * Title: registerAccount
	 * </p>
	 * <p>
	 * 功能描述:注册随寻通账号
	 * </p>
	 * 
	 * @param peopletel
	 */
	@Override
	public synchronized Object registerAccount(String peopletel) {
		if (StringUtils.isBlank(peopletel)) {
			return "手机号为空";
		}
		Integer peopleId = checkPeopletelIsExist(peopletel);
		if (peopleId == null) {
			StdPeopleinfo ent = new StdPeopleinfo();
			ent.setHoldid(1);
			ent.setCenterid(1);
			ent.setPeoplename("");
			ent.setPeopletype(1);// 1 管理员 2监视人
			ent.setPeopletel(peopletel);
			ent.setCreatetime(new Date());
			ent.setUpdatetime(ent.getCreatetime());
			ent.setPassword(MD5Util.MD5("123456").toLowerCase());
			ent.setParentid(-1);
			ent.setIsvalidate(false);
			// parentid = -1应该是谁支付修改为谁
			stdPeopleinfoMapper.insertSelective(ent);
			// mongodb
			// this.refreshUserCache(ent.getPeopleid());
			return ent.getPeopleid();
		} else {
			return peopleId;
		}
	}

	private Integer checkPeopletelIsExist(String peopletel) {
		StdPeopleinfoExample stdPeopleinfoExample = new StdPeopleinfoExample();
		stdPeopleinfoExample.createCriteria().andPeopletelEqualTo(peopletel).andIsdeletedEqualTo(false);
		List<StdPeopleinfo> peopleList = stdPeopleinfoMapper.selectByExample(stdPeopleinfoExample);
		if (CollectionUtils.isNotEmpty(peopleList)) {
			return peopleList.get(0).getPeopleid();
		}
		return null;
	}

	@Override
	public String getGuardians(String mdtid) {
		DeviceCache deviceCache = null;
		List<DeviceCache> deviceCaches = deviceCacheService.find(new Query(Criteria.where("mdtid").is(mdtid)).limit(1));
		if (deviceCaches == null || deviceCaches.size() == 0) {
		} else {
			deviceCache = deviceCaches.get(0);
		}
		if (deviceCache == null)
			return "";
		if (deviceCache.getUserids() != null) {
			List<Integer> peopleids = StringUtil.convertToInteger(deviceCache.getUserids());
			if (peopleids != null) {
				return StringUtils.join(peopleids, ",");
			}
			return "";
		}
		return "";
	}

	@Transactional
	@Override
	public Object correctPeopleTelBatch(HSSFWorkbook wb) {
		// 校验合法性
		/*
		 * String[] tableHead =
		 * {Constant.Excel.GRADE,Constant.Excel.TEACHERNAME,Constant.Excel.
		 * TELEPHONE, Constant.Excel.SCHOOL,Constant.Excel.CARD_SEND_COUNT};
		 * String[] excelTemplate = {Constant.Excel.TELEPHONE}; String
		 * checkExcel = ExcelUtil.checkExcel(wb,tableHead,excelTemplate,true);
		 * if (!Constant.TRUE.equals(checkExcel)) { // return checkExcel; return
		 * fail(checkExcel); }
		 */
		/*
		 * Map<String,String> tableMap = new HashMap<>();
		 * tableMap.put("classname", Constant.Excel.GRADE);
		 * tableMap.put("teachername", Constant.Excel.TEACHERNAME);
		 * tableMap.put("telephone", Constant.Excel.TELEPHONE);
		 * tableMap.put("schoolname", Constant.Excel.SCHOOL);
		 * tableMap.put("count", Constant.Excel.CARD_SEND_COUNT);
		 */
		Map<String, String> tableMap = new HashMap<>();
		String[] labels = { "学生姓名", "原家长手机号", "家长正确手机号" };
		String[] key = { "studentname", "oldphone", "newphone" };
		for (int i = 0; i < key.length; i++) {
			tableMap.put(key[i], labels[i]);
		}

		ExcelUtil excelUtil = new ExcelUtil();
		// 将excel数据读取到对象里
		List<ChangeParentTel> changeParentTels = null;
		try {
			changeParentTels = excelUtil.getExcelValue(tableMap, wb, ChangeParentTel.class);
		} catch (Exception e) {
			logger.equals("读取数据错误，请确认Excel表和里面的数据是否有误" + e.getCause());
			// BasicResult<T> res = new BasicResult<T>();
			// res.setCode(AdminConstants.CODE_500);
			// res.setMsg("读取数据错误，请确认Excel表和里面的数据是否有误");
			// return res;
			return new Result(com.suixun.enums.APICode.HTTP_900.setCustomMsg("读取数据错误，请确认Excel表和里面的数据是否有误"), null);
		}
		// 检查数据有效性，1，验证手机号，2，去除重复记录，3，去重
		StringBuffer sb = new StringBuffer();
		// Set<String> oldphoneset = new HashSet<String>();//Set < E >
		// 是一个不包含重复元素的 collection
		// Set<String> newphoneset = new HashSet<String>();
		List<String> oldphonelist = new ArrayList<String>();
		List<String> newphonelist = new ArrayList<String>();
		List<String> exitnewphonelist = new ArrayList<String>();
		List<String> exitoldphonelist = new ArrayList<String>();
		List<String> studentnamelist = new ArrayList<String>();
		for (ChangeParentTel changeParentTel : changeParentTels) {
			String oldphone = changeParentTel.oldphone.replaceAll(" ", "");
			String newphone = changeParentTel.newphone.replaceAll(" ", "");
			String studentname = changeParentTel.studentname.replaceAll(" ", "");
			changeParentTel.oldphone = oldphone;
			changeParentTel.newphone = newphone;
			changeParentTel.studentname = studentname;
			if (StringUtils.isEmpty(studentname)) {
				sb.append("原手机号" + oldphone + "对应的学生姓名为空；");
				continue;
			}
			if (StringUtils.isEmpty(oldphone)) {
				sb.append("新手机号" + newphone + "对应的原手机号为空；");
				continue;
			}
			if (StringUtils.isEmpty(newphone)) {
				sb.append("原手机号" + oldphone + "对应的新手机号为空；");
				continue;
			}
			if (!StringUtils.isNumeric(oldphone)) {
				sb.append("手机号" + oldphone + "不合法；");
				continue;
			}
			if (!StringUtils.isNumeric(newphone)) {
				sb.append("手机号" + newphone + "不合法；");
				continue;
			}
			if (oldphonelist.contains(oldphone)) {
				sb.append("原手机号" + oldphone + "有重复；");
				continue;
			} else if (newphonelist.contains(newphone)) {
				sb.append("新手机号" + newphone + "有重复；");
				continue;
			}
			studentnamelist.add(studentname);
			oldphonelist.add(oldphone);
			newphonelist.add(newphone);
		}
		// 原手机是否存在这样的账户
		StdPeopleinfoExample stdPeopleinfoExampleold = new StdPeopleinfoExample();
		stdPeopleinfoExampleold.createCriteria().andPeopletelIn(oldphonelist);
		List<StdPeopleinfo> stdPeopleinfoolds = stdPeopleinfoMapper.selectByExample(stdPeopleinfoExampleold);
		// if(stdPeopleinfoolds.size() <= oldphonelist.size()){
		for (StdPeopleinfo stdPeopleinfo : stdPeopleinfoolds) {
			exitoldphonelist.add(stdPeopleinfo.getPeopletel());
		}
		// }
		// 新手机号是否已经注册过
		StdPeopleinfoExample stdPeopleinfoExamplenew = new StdPeopleinfoExample();
		stdPeopleinfoExamplenew.createCriteria().andPeopletelIn(newphonelist);
		List<StdPeopleinfo> stdPeopleinfonews = stdPeopleinfoMapper.selectByExample(stdPeopleinfoExamplenew);
		// int len2 = stdPeopleinfonews.size();
		// if(len2 < newphonelist.size()){
		for (StdPeopleinfo stdPeopleinfo : stdPeopleinfonews) {
			exitnewphonelist.add(stdPeopleinfo.getPeopletel());
		}
		// }
		for (String oldphone1 : oldphonelist) {
			if (!exitoldphonelist.contains(oldphone1)) {
				sb.append("原手机号为" + oldphone1 + "在系统中并不存在这样的账户；");
				int index = oldphonelist.indexOf(oldphone1);
				oldphonelist.remove(index);
				newphonelist.remove(index);
				studentnamelist.remove(index);
				// stdPeopleinfoolds.remove(index);

			}
		}
		for (String newphone2 : newphonelist) {
			if (exitnewphonelist.contains(newphone2)) {
				sb.append("新手机号为" + newphone2 + "的用户已经存在不能更换手机号成它；");
				int index = newphonelist.indexOf(newphone2);
				for (StdPeopleinfo stdPeopleinfo : stdPeopleinfoolds) {
					if (stdPeopleinfo.getPeopletel().equals(oldphonelist.get(index)))
						;
					stdPeopleinfoolds.remove(stdPeopleinfo);
					break;
				}
				newphonelist.remove(index);
				oldphonelist.remove(index);
				studentnamelist.remove(index);
				// stdPeopleinfoolds.remove(index);
			}
		}
		// 家校通更换手机
		String url = getProperties("/webconfig.properties", "JXT_URL");
		// url = "http://localhost:8088";
		url += "/jxt-commonbackground/ajaxStudent.do";
		String param = "method=ajaxModifyBabyParentMobileBatch&babynames=" + String.join(",", studentnamelist)
				+ "&oldphones=" + String.join(",", oldphonelist) + "&newphones=" + String.join(",", newphonelist)
				+ "&token=324jgoi46iofrjoigjr65655424";
		String result = HttpUtil.sendPost(url, param, false);
		Result result2 = new Gson().fromJson(result, Result.class);
		// String[] data = (String[]) result2.data;
		List<String> data = (List<String>) result2.data;
		String sucPhones = data.get(0);// data[0];
		String jxt_errormsg = data.get(1);// data[1];

		List<String> sucPhoneslist = Arrays.asList(sucPhones.split(","));
		for (String oldphone3 : oldphonelist) {
			if (!sucPhoneslist.contains(oldphone3)) {
				sb.append("原手机号为" + oldphone3 + "在家校通更换手机号失败；");
				int index = oldphonelist.indexOf(oldphone3);
				for (StdPeopleinfo stdPeopleinfo : stdPeopleinfoolds) {
					if (stdPeopleinfo.getPeopletel().equals(oldphonelist.get(index)))
						;
					stdPeopleinfoolds.remove(stdPeopleinfo);
					break;
				}
				oldphonelist.remove(index);
				newphonelist.remove(index);
				studentnamelist.remove(index);
			}
		}
		for (StdPeopleinfo stdPeopleinfo : stdPeopleinfoolds) {
			int index = oldphonelist.indexOf(stdPeopleinfo.getPeopletel());
			StdPeopleinfo update = new StdPeopleinfo();
			update.setPeopleid(stdPeopleinfo.getPeopleid());
			update.setPeopletel(newphonelist.get(index));
			try {
				stdPeopleinfoMapper.updateByPrimaryKeySelective(update);
			} catch (Exception e) {
				sb.append("原手机号为" + oldphonelist.get(index) + "的用户在随寻更新手机失败；");
			}

		}
		logger.error(sb.toString() + "||" + jxt_errormsg);
		// return success("操作完成"+sb.toString()+"||"+jxt_errormsg);

		return new Result(com.suixun.enums.APICode.SUCCESS, sb.toString() + "；" + jxt_errormsg);

	}

	/**
	 * 三、
	 * 使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法
	 * getResourceAsStream(name)方法的参数必须是包路径+文件名+.后缀 否则会报空指针异常
	 * 
	 */
	public String getProperties(String Propertiesfile, String Propertiesname) {
		Properties prop = new Properties();
		InputStream is = PropertiesUtil.class.getClassLoader()
				// .getResourceAsStream("com/util/prop.properties");
				.getResourceAsStream(Propertiesfile);
		try {
			prop.load(is);

		} catch (IOException e) {
			e.printStackTrace();
		}
		return prop.getProperty(Propertiesname);
	}

	@Override
	public String getGuardiansByObjectId(Integer objectId) {
		if (objectId == null) {
			return null;
		}
		List<StdPeopleinfo> peopleInfoList = deviceServiceDAO.getPeopleListByObjectId(objectId);
		if (CollectionUtils.isEmpty(peopleInfoList)) {
			return null;
		}
		List<Integer> peopleIdList = new ArrayList<>();
		peopleInfoList.forEach(peopleInfo -> peopleIdList.add(peopleInfo.getPeopleid()));
		return StringUtils.join(peopleIdList, ",");
	}

	@Override
	public StdPeopleinfo getPeopleinfo(String peopletel) {
		if(StringUtils.isBlank(peopletel)) {
			return null;
		}
		StdPeopleinfoExample stdPeopleinfoExample = new StdPeopleinfoExample();
		stdPeopleinfoExample.createCriteria().andPeopletelEqualTo(peopletel).andIsdeletedEqualTo(false);
		List<StdPeopleinfo> peopleinfoList = stdPeopleinfoMapper.selectByExample(stdPeopleinfoExample);
		if(CollectionUtils.isEmpty(peopleinfoList)) {
			return null;
		}
		return peopleinfoList.get(0);
	}
}
